package com.degon.hsyl.imagepreview.util;


import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.widget.Toast;

import androidx.annotation.NonNull;


import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;

public class DownloadImageUtil {


    private static String url;
    //    private static Bitmap bitmap;
    private static String saveMessage = "失败";
    private static Context context;
    private static ProgressDialog saveDialog;

    public static void DownloadImage(String imageUrl, Context mContext) {
        url = imageUrl;
        context = mContext;
        saveDialog = ProgressDialog.show(context, "保存图片", "图片正在保存中...", true);
        new Thread(saveImageRunnable).start();
    }

    private static Runnable saveImageRunnable = new Runnable() {
        @Override
        public void run() {
            try {
                URL conn = new URL(url);
                InputStream inputStream = conn.openStream();
                Bitmap bitmap = BitmapFactory.decodeStream(inputStream);

                //保存图片到本地
                saveImage(bitmap);
                saveMessage = "图片保存成功!";
            } catch (IOException e) {
                e.printStackTrace();
                saveMessage = "下载失败,请稍后重试...";
            }
            messageHandler.sendMessage(messageHandler.obtainMessage());
        }
    };

    private static void saveImage(Bitmap bitmap) throws IOException {
        File dirFile = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM) + "/MaiYa");
        if (!dirFile.exists()) {
            dirFile.mkdir();
        }

        File imageFile = new File(dirFile.getPath() + "/" + System.currentTimeMillis() + ".jpg");

        FileOutputStream fileOutputStream = new FileOutputStream(imageFile.getPath());
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fileOutputStream);
        fileOutputStream.close();

        Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        Uri uri = Uri.fromFile(imageFile);
        intent.setData(uri);
        context.sendBroadcast(intent);
    }

    @SuppressLint("HandlerLeak")
    private static final Handler messageHandler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            saveDialog.dismiss();
            Toast.makeText(context, saveMessage, Toast.LENGTH_SHORT).show();
        }
    };

}

